// pages/shop/shopDt.js
//获取应用实例
var app = getApp();
var memberUtil=require('../../utils/memberUtil');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    image: [
      { url: app.globalData.baseImageUrl+'/images/p_3.jpg' },
      { url: app.globalData.baseImageUrl+'/images/p_3.jpg' }
    ],
    toView: 'inToView01',
    hideShopPopup:true,
    imagesUrl: app.globalData.baseImageUrl,
    serverImageUrl:app.globalData.baseUrl,
    goods:{},
    goodsGuiGe:null,
    shopType:"addShopCar",
    buyNumber:1,
    buyNumMin: 1,
    buyNumMax: 0,
    price:0,
    goodsImage:null,
    guige:false,
    guigeList:null,
    belongto:0,//0商城，1积分商城,
    goodsDetailImages:[]
  },
  /**
   * 展示商品详情
   */
  zhanshishangping:function(obj){
    var that = this;
    wx.showLoading({
      title: '加载中'
    })
    //商品详情
      var goodsIdJson={goodsId:obj};
      wx.request({
        url: app.globalData.baseUrl + "/goods/findGoodsInfoByGoodsId",
        data: JSON.stringify(goodsIdJson),
        header: app.globalData.headerPost,
        method: 'POST',
        success: function (e) {
          var content=e.data.content;
          var contents=content.split(" alt=\"\" /><img ");
          var itemsContent=[];
          for(var i in contents){
            var s=contents[i];
         if(i==(contents.length-1)){
              itemsContent.push(s.substring(s.indexOf("src=\"")+7,s.indexOf("alt")-2));
            }else{
              itemsContent.push(s.substring(s.indexOf("src=\"")+7,s.indexOf(".jpg")+4));
            }
          }
          var srcStr=content.substring(content.indexOf("src=\"")+5,content.indexOf("alt")-2);
          content=srcStr;
          e.data.content=content;
          if(e.data.goodsSpecificationList.length>1){//有规格商品
            var gg="";
            var list1=[];
            for(var i=0;i< e.data.goodsSpecificationList.length;i++) {
              gg = e.data.goodsSpecificationList[i];
              if (i == 0) {
                list1.push({id: gg.id, name: gg.name, price: gg.price,stock:gg.stock, flag: true});
              } else {
                list1.push({id: gg.id, name: gg.name, price: gg.price,stock:gg.stock, flag: false});
              }
            }
            that.setData({
              goodsDetailImages:itemsContent,
              goodsGuiGe: e.data.goodsSpecificationList,
              guigestock:e.data.goodsSpecificationList[0].stock,
              goods:{
                id: e.data.id,
                categoryId: e.data.categoryId,
                goodsName: e.data.goodsName,
                goodsDescription: e.data.goodsSpecificationList[0].description,
                goodsPic1: e.data.goodsSpecificationList[0].pic1,
                goodsPic2: e.data.goodsSpecificationList[0].pic2,
                goodsPic3: e.data.goodsSpecificationList[0].pic3,
                content: e.data.goodsSpecificationList[0].content,
                goodsNumber: e.data.goodsNumber,
                price: e.data.goodsSpecificationList[0].price,
                marketPrice: e.data.goodsSpecificationList[0].marketPrice,
                totalStock: e.data.goodsSpecificationList[0].stock,
                integral: e.data.goodsSpecificationList[0].integral,
                belongTo: e.data.goodsSpecificationList[0].belongTo,
                totalComment: e.data.totalComment,
                totalCollect: e.data.totalCollect,
                totalSalesVolume: e.data.totalSalesVolume,
                monthSalesVolume: e.data.monthSalesVolume
              },
              price: e.data.goodsSpecificationList[0].price,
              submitGoods:{
                memberId:app.globalData.loginUserInfo.userInfo.id,
                goodsId:null,
                goodsSpecificationId: e.data.goodsSpecificationList[0].id,
                isSpecificationGoods:0,
                specificationName: e.data.goodsSpecificationList[0].name,
                buyNumber:1,
                goodsName:null,
                goodsPrice: e.data.goodsSpecificationList[0].price,
                totalPrice: e.data.goodsSpecificationList[0].price,
                goodsConsumerMoney: e.data.goodsSpecificationList[0].price,
                totalConsumerMoney: e.data.goodsSpecificationList[0].price,
                belongTo: e.data.goodsSpecificationList[0].belongTo
              },
              guige:true,
              guigeList:list1,
              belongto:e.data.belongTo
            })
          }else {//没有规格
            that.setData({
              goodsDetailImages:itemsContent,
              guigestock:e.data.totalStock,
              goods: e.data,
              price: e.data.price,
              submitGoods: {
                memberId: app.globalData.loginUserInfo.userInfo.id,
                goodsId: e.data.id,
                goodsSpecificationId:null,
                isSpecificationGoods: 1,
                specificationName: null,
                buyNumber: 1,
                goodsName: e.data.goodsName,
                goodsPrice: e.data.price,
                totalPrice: e.data.price,
                goodsConsumerMoney: e.data.price,
                totalConsumerMoney: e.data.price,
                belongTo: e.data.belongTo
              },
              belongto:e.data.belongTo
            })
          }
          var imgs=[];
          if(that.data.goods.goodsPic1) {
            imgs.push({url: app.globalData.baseUrl + "/" + that.data.goods.goodsPic1});
          }
          if(that.data.goods.goodsPic2) {
            imgs.push({url: app.globalData.baseUrl + "/" + that.data.goods.goodsPic2});
          }
          if(that.data.goods.goodsPic3) {
            imgs.push({url: app.globalData.baseUrl + "/" + that.data.goods.goodsPic3});
          }
          that.setData({
            image:imgs,
            goodsImage:imgs[0].url
          })
          wx.hideLoading();
        },
        fail: function (e) {
          wx.hideLoading();
          wx.showLoading({
            title: '系统开小差了',
            mask: true
          });
        }
      })
  },
  /**
 * 规格选择弹出框标
 */
  bindGuiGeTap: function () {
    this.setData({
      hideShopPopup: false
    })
  },
  /**
  * 规格选择弹出框隐藏
  */
  closePopupTap: function () {
    this.setData({
      hideShopPopup: true
    })
  },
  //减数量
  numJianTap: function () {
    var kucun=this.data.goods.totalStock;
    if (this.data.buyNumber > this.data.buyNumMin && this.data.buyNumber<=Number(kucun)) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  //加数量
  numJiaTap: function () {
      var kucun=this.data.goods.totalStock;
    if ((this.data.buyNumber >= this.data.buyNumMin) && (this.data.buyNumber<Number(kucun))) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this;
    that.setData({
      userInfo: wx.getStorageSync("loginUserInfo").userInfo==undefined?"":wx.getStorageSync("loginUserInfo").userInfo
    });
    var goodsId=options.goodsId;
    if(goodsId){
      that.zhanshishangping(goodsId);
    }
    memberUtil.shareDL(app,options,"2",that);
    /*if(that.data.userInfo.id==undefined) {
      memberUtil.getLogin(app,0,1,that,2);
    }*/
  },
  //加入购物车
  toAddShopCar: function () {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },
  //立即购买
  tobuy: function () {
    this.setData({
      shopType: "tobuy"
    });
    this.bindGuiGeTap();
  },
  //立即购买提交
  buyNow:function(e){
    var that=this;
    var mallGoodsParamJson=null;
    var totalPrice=0;
    var yunfei=0;
      var kucun=that.data.goods.totalStock;
    if(that.data.goodsGuiGe) {//有规格
      var price="";
      var id="";
      var name="";
      for(var a=0;a<that.data.guigeList.length;a++){
        if(that.data.guigeList[a].flag){
          price=that.data.guigeList[a].price;
          id=that.data.guigeList[a].id;
          name=that.data.guigeList[a].name;
        }
      }
        totalPrice=Number(price)*that.data.buyNumber;
      if(totalPrice<199){
          yunfei=10;
      }
      mallGoodsParamJson = {
        memberId: app.globalData.loginUserInfo.userInfo.id,
        goodsId: that.data.goods.id,
        goodsSpecificationId: id,
        isSpecificationGoods: 0,
        specificationName: name,
        buyNumber:that.data.buyNumber,
        goodsName: that.data.goods.goodsName,
        goodsPrice: price,
        totalPrice: totalPrice,
        goodsConsumerMoney: price,
        paymentConsumerMoney: Number(price)*that.data.buyNumber,
        belongTo: that.data.goods.belongTo,
        receivingAddressId:"",
        buyerMessage:"",
        buyerNickname:"",
        goodsPicUrl:that.data.goodsImage,
          expressFee:yunfei
      }
    }else{//没有规格
      mallGoodsParamJson=that.data.submitGoods;
      var buyN=that.data.buyNumber;
      var price=that.data.submitGoods.goodsPrice;
        totalPrice=Number(buyN)*Number(price);
        if(totalPrice<199){
            yunfei=10;
        }
      mallGoodsParamJson.buyNumber=buyN;
      mallGoodsParamJson.totalPrice=totalPrice;
     mallGoodsParamJson.totalConsumerMoney=totalPrice;
      mallGoodsParamJson.isSpecificationGoods=1;
      mallGoodsParamJson.paymentConsumerMoney=mallGoodsParamJson.goodsConsumerMoney;
      mallGoodsParamJson.buyerMessage="";
      mallGoodsParamJson.buyerNickname="";
      mallGoodsParamJson["expressFee"]=yunfei;
      mallGoodsParamJson.goodsPicUrl=that.data.goodsImage;
    }
  if(kucun<that.data.buyNumber){
      wx.showToast({
          title: '库存不足，请等待补充货源！',
          icon: 'none',
          duration: 3000
      })
      return false;
  }
    var requestUrl="/order/mallGoodsBuyNow";//商城url
    if(that.data.belongto==1){//积分
      requestUrl="/order/integralMallGoodsBuyNow";
      mallGoodsParamJson.goodsIntegral=mallGoodsParamJson.goodsPrice;
      mallGoodsParamJson.totalIntegral=mallGoodsParamJson.totalPrice;
    }

    //商品立即购买
    wx.showLoading({
      title: '数据加载中',
      mask: true
    });
    wx.request({
      url: app.globalData.baseUrl +requestUrl,
      data: JSON.stringify(mallGoodsParamJson),
      header: app.globalData.headerPost,
      method: 'POST',
      success: function (e) {
        if(e.data.status==200) {
          var goodsInfo={
            orderInfo: e.data.data,
            mallGoodsParamJson:mallGoodsParamJson,
            goodsImage:that.data.goodsImage,
            kucun:that.data.goods.totalStock
          }
          wx.setStorageSync("goodsInfo", goodsInfo);
          wx.redirectTo({
            url: '/pages/shop/placeOrder'
          })

        }else{
          wx.showToast({
            title: '系统开小差去了',
            icon: 'none',
            duration: 1000
          })
        }
        wx.hideLoading();
      },
      fail: function (e) {
        wx.showLoading({
          title: '系统开小差了',
          mask: true
        });
        wx.hideLoading();
      }
    })


  },
  //处理规格
  guigechuli:function(e){
    var that=this;
    var price= e.currentTarget.dataset.price;
    var id= e.currentTarget.dataset.id;
    var name= e.currentTarget.dataset.name;
    var stock= e.currentTarget.dataset.stock;
    var ggList=[];
    var buyNumber=that.data.buyNumber;
    for(var a=0;a<this.data.guigeList.length;a++){
      if(id==this.data.guigeList[a].id){
        ggList.push({id:id,name:name,price:price,stock:stock,flag:true});
        if(buyNumber>stock){
          buyNumber=stock;
        }
      }else{
        this.data.guigeList[a].flag=false;
        ggList.push(this.data.guigeList[a])
      }
    }
    this.setData({
      guigeList:ggList,
      price:Number(price),
      guigestock:stock,
        buyNumber:buyNumber
    })
  },
  //组装购物车
  addShopCarZuZhuang:function(e){
    var that=this;
    var mallGoodsParamJson=null;
    var totalPrice=0;
    if(that.data.goodsGuiGe) {//有规格
      var price="";
      var id="";
      var name="";
      for(var a=0;a<that.data.guigeList.length;a++){
        if(that.data.guigeList[a].flag){
          price=that.data.guigeList[a].price;
          id=that.data.guigeList[a].id;
          name=that.data.guigeList[a].name;
        }
      }
      mallGoodsParamJson = {
        memberId: app.globalData.loginUserInfo.userInfo.id,
        goodsId: that.data.goods.id,
        goodsSpecificationId: id,
        isSpecificationGoods: 0,
        specificationName: name,
        buyNumber:that.data.buyNumber,
        goodsName: that.data.goods.goodsName,
        goodsPrice: price,
        totalPrice: Number(price)*that.data.buyNumber,
        goodsConsumerMoney: price,
        totalConsumerMoney: Number(price)*that.data.buyNumber,
        belongTo: that.data.goods.belongTo,
        goodsPicUrl:that.data.goodsImage
      }
    }else{//没有规格
      mallGoodsParamJson=this.data.submitGoods;
      var buyN=this.data.buyNumber;
      var price=this.data.submitGoods.goodsPrice;
      var totalP=Number(buyN)*Number(price);
      mallGoodsParamJson.buyNumber=buyN;
      mallGoodsParamJson.totalPrice=totalP;
      mallGoodsParamJson.totalConsumerMoney=totalP;
      mallGoodsParamJson.isSpecificationGoods=1;
      mallGoodsParamJson.goodsPicUrl=that.data.goodsImage;
    }

    var addShopCarUrl="/shoppingCartItem/addMallGoods";
    if(that.data.belongto==1){
      //积分购物车
      addShopCarUrl="/shoppingCartItem/addIntegralMallGoods";
      mallGoodsParamJson.goodsIntegral=mallGoodsParamJson.goodsPrice;
      mallGoodsParamJson.totalIntegral=mallGoodsParamJson.totalPrice;
    }

    //商品添加购物车
    wx.request({
      url: app.globalData.baseUrl + addShopCarUrl,
      data: JSON.stringify(mallGoodsParamJson),
      header: app.globalData.headerPost,
      method: 'POST',
      success: function (e) {
        if(e.data.status==200) {
          wx.showToast({
            title: '添加购物车成功',
            icon: 'success',
            duration: 2000,
            success:function(){
              that.closePopupTap();
            }
          })

        }else{
          wx.showToast({
            title: '添加购物车失败',
            icon: 'none',
            duration: 2000
          })
        }
      },
      fail: function (e) {
        wx.showToast({
          title: '系统开小差了',
          icon: 'none',
          duration: 2000
        });
      }
    })


  },
    //页面跳转
    goodsDetailNavigate:function(e){
         wx.switchTab({
            url: '/pages/tabBar/shopcar/car'
        })
    },
  //卡卷提示
  kajuan:function(){
    wx.showToast({
      title: '此模块工程师正在积极升级，敬请期待！',
      icon: 'none',
      duration: 1000
    })
  },
  imageLoad:function(){

    var n=0;
    var time = setInterval(function () {
        if(n>2) {
          clearInterval(time);
          wx.hideLoading();
        }else{
          n++;
          wx.showLoading({
            title: ' 图片正在加载',
            mask: true
          });
        }
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("监听页面初次渲染完成");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("页面显示");
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("页面隐藏");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  console.log("页面卸载");
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log("用户下拉动作");
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("上拉触底事件的处理函数");
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '我的二维码',
      path: "/pages/shop/shopDt?parentId=" + this.data.userInfo.id + "&enterType=0&goodsId="+this.data.goods.id,
      imageUrl: app.globalData.loginUserInfo.erweimaUrl
    }
  }
})